winsafe\gui\native_controls/
edit.rs

1use std::any::Any;
2use std::marker::PhantomPinned;
3use std::pin::Pin;
4use std::sync::Arc;
5
6use crate::co;
7use crate::decl::*;
8use crate::gui::{privs::*, *};
9use crate::msg::*;
10use crate::prelude::*;
11
12struct EditObj {
13	base: BaseCtrl,
14	events: BaseCtrlEvents,
15	_pin: PhantomPinned,
16}
17
18native_ctrl! { Edit: EditObj => GuiEventsEdit;
19	/// Native
20	/// [edit](https://learn.microsoft.com/en-us/windows/win32/controls/about-edit-controls)
21	/// (text box) control.
22}
23
24impl Edit {
25	/// Instantiates a new `Edit` object, to be created on the parent window
26	/// with [`HWND::CreateWindowEx`](crate::HWND::CreateWindowEx).
27	///
28	/// # Panics
29	///
30	/// Panics if the parent window was already created – that is, you cannot
31	/// dynamically create an `Edit` in an event closure.
32	///
33	/// # Examples
34	///
35	/// ```no_run
36	/// use winsafe::{self as w, prelude::*, gui};
37	///
38	/// let wnd: gui::WindowMain; // initialized somewhere
39	/// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
40	///
41	/// let txt = gui::Edit::new(
42	///     &wnd,
43	///     gui::EditOpts {
44	///         position: gui::dpi(10, 10),
45	///         width: gui::dpi_x(120),
46	///         ..Default::default()
47	///     },
48	/// );
49	/// ```
50	#[must_use]
51	pub fn new(parent: &(impl GuiParent + 'static), opts: EditOpts) -> Self {
52		let ctrl_id = auto_id::set_if_zero(opts.ctrl_id);
53		let new_self = Self(Arc::pin(EditObj {
54			base: BaseCtrl::new(ctrl_id),
55			events: BaseCtrlEvents::new(parent, ctrl_id),
56			_pin: PhantomPinned,
57		}));
58
59		let self2 = new_self.clone();
60		let parent2 = parent.clone();
61		let text2 = opts.text.to_owned();
62		parent
63			.as_ref()
64			.before_on()
65			.wm(parent.as_ref().wnd_ty().creation_msg(), move |_| {
66				self2.0.base.create_window(
67					opts.window_ex_style,
68					"EDIT",
69					Some(&text2),
70					opts.window_style | opts.control_style.into(),
71					opts.position.into(),
72					SIZE::with(opts.width, opts.height),
73					&parent2,
74				);
75				ui_font::set(self2.hwnd());
76				parent2
77					.as_ref()
78					.add_to_layout(self2.hwnd(), opts.resize_behavior);
79				Ok(0) // ignored
80			});
81
82		new_self.default_message_handlers(parent);
83		new_self
84	}
85
86	/// Instantiates a new `Edit` object, to be loaded from a dialog resource
87	/// with [`HWND::GetDlgItem`](crate::HWND::GetDlgItem).
88	///
89	/// # Panics
90	///
91	/// Panics if the parent dialog was already created – that is, you cannot
92	/// dynamically create an `Edit` in an event closure.
93	#[must_use]
94	pub fn new_dlg(
95		parent: &(impl GuiParent + 'static),
96		ctrl_id: u16,
97		resize_behavior: (Horz, Vert),
98	) -> Self {
99		let new_self = Self(Arc::pin(EditObj {
100			base: BaseCtrl::new(ctrl_id),
101			events: BaseCtrlEvents::new(parent, ctrl_id),
102			_pin: PhantomPinned,
103		}));
104
105		let self2 = new_self.clone();
106		let parent2 = parent.clone();
107		parent.as_ref().before_on().wm_init_dialog(move |_| {
108			self2.0.base.assign_dlg(&parent2);
109			parent2
110				.as_ref()
111				.add_to_layout(self2.hwnd(), resize_behavior);
112			Ok(true) // ignored
113		});
114
115		new_self.default_message_handlers(parent);
116		new_self
117	}
118
119	fn default_message_handlers(&self, parent: &(impl GuiParent + 'static)) {
120		let self2 = self.clone();
121		let parent2 = parent.clone();
122		parent
123			.as_ref()
124			.before_on()
125			.wm_command(self.ctrl_id(), co::EN::CHANGE, move || {
126				// EN_CHANGE is first sent to the control before CreateWindowEx()
127				// returns, so if the user handles EN_CHANGE, the Edit HWND won't be
128				// set yet. So we set the HWND here.
129				if *self2.hwnd() == HWND::NULL {
130					let hctrl = parent2
131						.as_ref()
132						.hwnd()
133						.GetDlgItem(self2.ctrl_id())
134						.expect(DONTFAIL);
135					self2.0.base.set_hwnd(hctrl);
136				}
137				Ok(())
138			});
139	}
140
141	/// Hides any balloon tip by sending an
142	/// [`em::HideBalloonTip`](crate::msg::em::HideBalloonTip) message.
143	pub fn hide_balloon_tip(&self) -> SysResult<()> {
144		unsafe { self.hwnd().SendMessage(em::HideBalloonTip {}) }
145	}
146
147	/// Limits the number of characters that can be type by sending an
148	/// [`em::SetLimitText`](crate::msg::em::SetLimitText) message.
149	pub fn limit_text(&self, max_chars: Option<u32>) {
150		unsafe {
151			self.hwnd().SendMessage(em::SetLimitText { max_chars });
152		}
153	}
154
155	/// Replaces the currently selected text by sending an
156	/// [`em::ReplaceSel`](crate::msg::em::ReplaceSel) message.
157	pub fn replace_selection(&self, text: &str) {
158		let text16 = WString::from_str(text);
159		unsafe {
160			self.hwnd().SendMessage(em::ReplaceSel {
161				can_be_undone: true,
162				replacement_text: text16,
163			})
164		}
165	}
166
167	/// Sets the selection range of the text by sending an
168	/// [`em::SetSel`](crate::msg::em::SetSel) message.
169	///
170	/// # Examples
171	///
172	/// Selecting all text in the control:
173	///
174	/// ```no_run
175	/// use winsafe::{self as w, prelude::*, gui};
176	///
177	/// let my_edit: gui::Edit; // initialized somewhere
178	/// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
179	/// # let my_edit = gui::Edit::new(&wnd, gui::EditOpts::default());
180	///
181	/// my_edit.set_selection(0, -1);
182	/// ```
183	///
184	/// Clearing the selection:
185	///
186	/// ```no_run
187	/// use winsafe::gui;
188	///
189	/// let my_edit: gui::Edit; // initialized somewhere
190	/// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
191	/// # let my_edit = gui::Edit::new(&wnd, gui::EditOpts::default());
192	///
193	/// my_edit.set_selection(-1, -1);
194	/// ```
195	pub fn set_selection(&self, start: i32, end: i32) {
196		unsafe {
197			self.hwnd().SendMessage(em::SetSel { start, end });
198		}
199	}
200
201	/// Sets the text by calling
202	/// [`HWND::SetWindowText`](crate::HWND::SetWindowText).
203	pub fn set_text(&self, text: &str) -> SysResult<()> {
204		self.hwnd().SetWindowText(text)?;
205		Ok(())
206	}
207
208	/// Displays a balloon tip by sending an
209	/// [`em::ShowBalloonTip`](crate::msg::em::ShowBalloonTip) message.
210	pub fn show_ballon_tip(&self, title: &str, text: &str, icon: co::TTI) -> SysResult<()> {
211		let mut title16 = WString::from_str(title);
212		let mut text16 = WString::from_str(text);
213
214		let mut info = EDITBALLOONTIP::default();
215		info.set_pszTitle(Some(&mut title16));
216		info.set_pszText(Some(&mut text16));
217		info.ttiIcon = icon;
218
219		unsafe { self.hwnd().SendMessage(em::ShowBalloonTip { info: &info }) }
220	}
221
222	/// Retrieves the text by calling
223	/// [`HWND::GetWindowText`](crate::HWND::GetWindowText).
224	#[must_use]
225	pub fn text(&self) -> SysResult<String> {
226		self.hwnd().GetWindowText()
227	}
228}
229
230/// Options to create an [`Edit`](crate::gui::Edit) programmatically with
231/// [`Edit::new`](crate::gui::Edit::new).
232pub struct EditOpts<'a> {
233	/// Text of the control to be
234	/// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
235	///
236	/// Defaults to empty string.
237	pub text: &'a str,
238	/// Left and top position coordinates of control within parent's client
239	/// area, to be
240	/// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
241	///
242	/// Defaults to `gui::dpi(0, 0)`.
243	pub position: (i32, i32),
244	/// Control width to be
245	/// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
246	///
247	/// Defaults to `gui::dpi_x(100)`.
248	pub width: i32,
249	/// Control height to be
250	/// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
251	///
252	/// Defaults to `gui::dpi_y(23)`.
253	///
254	/// **Note:** You should change the default height only in a multi-line
255	/// edit, otherwise it will look off.
256	pub height: i32,
257	/// Edit styles to be
258	/// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
259	///
260	/// Defaults to `ES::AUTOHSCROLL | ES::NOHIDESEL`.
261	///
262	/// Suggestions:
263	/// * add `ES::PASSWORD` for a password input;
264	/// * add `ES::NUMBER` to accept only numbers;
265	/// * replace with `ES::MULTILINE | ES::WANTRETURN | ES::AUTOVSCROLL | ES::NOHIDESEL` for a multi-line edit.
266	pub control_style: co::ES,
267	/// Window styles to be
268	/// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
269	///
270	/// Defaults to `WS::CHILD | WS::GROUP | WS::TABSTOP | WS::VISIBLE`.
271	pub window_style: co::WS,
272	/// Extended window styles to be
273	/// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
274	///
275	/// Defaults to `WS_EX::LEFT | WS_EX::CLIENTEDGE`.
276	pub window_ex_style: co::WS_EX,
277
278	/// The control ID.
279	///
280	/// Defaults to an auto-generated ID.
281	pub ctrl_id: u16,
282	/// Horizontal and vertical behavior of the control when the parent window
283	/// is resized.
284	///
285	/// **Note:** You should use `Vert::Resize` only in a multi-line edit.
286	///
287	/// Defaults to `(gui::Horz::None, gui::Vert::None)`.
288	pub resize_behavior: (Horz, Vert),
289}
290
291impl<'a> Default for EditOpts<'a> {
292	fn default() -> Self {
293		Self {
294			text: "",
295			position: dpi(0, 0),
296			width: dpi_x(100),
297			height: dpi_y(23),
298			control_style: co::ES::AUTOHSCROLL | co::ES::NOHIDESEL,
299			window_style: co::WS::CHILD | co::WS::GROUP | co::WS::TABSTOP | co::WS::VISIBLE,
300			window_ex_style: co::WS_EX::LEFT | co::WS_EX::CLIENTEDGE,
301			ctrl_id: 0,
302			resize_behavior: (Horz::None, Vert::None),
303		}
304	}
305}